Using Reflection.Emit to emit a "using (x) { ... }" block?

Posted by Lasse V. Karlsen on Stack Overflow See other posts from Stack Overflow or by Lasse V. Karlsen
Published on 2010-06-08T15:49:25Z Indexed on 2010/06/08 15:52 UTC
Read the original article Hit count: 294

I'm trying to use Reflection.Emit in C# to emit a using (x) { ... } block.

At the point I am in code, I need to take the current top of the stack, which is an object that implements IDisposable, store this away in a local variable, implement a using block on that variable, and then inside it add some more code (I can deal with that last part.)

Here's a sample C# piece of code I tried to compile and look at in Reflector:

public void Test()
{
    TestDisposable disposable = new TestDisposable();
    using (disposable)
    {
        throw new Exception("Test");
    }
}

This looks like this in Reflector:

.method public hidebysig instance void Test() cil managed
{
    .maxstack 2
    .locals init (
        [0] class LVK.Reflection.Tests.UsingConstructTests/TestDisposable disposable,
        [1] class LVK.Reflection.Tests.UsingConstructTests/TestDisposable CS$3$0000,
        [2] bool CS$4$0001)
    L_0000: nop 
    L_0001: newobj instance void LVK.Reflection.Tests.UsingConstructTests/TestDisposable::.ctor()
    L_0006: stloc.0 
    L_0007: ldloc.0 
    L_0008: stloc.1 
    L_0009: nop 
    L_000a: ldstr "Test"
    L_000f: newobj instance void [mscorlib]System.Exception::.ctor(string)
    L_0014: throw 
    L_0015: ldloc.1 
    L_0016: ldnull 
    L_0017: ceq 
    L_0019: stloc.2 
    L_001a: ldloc.2 
    L_001b: brtrue.s L_0024
    L_001d: ldloc.1 
    L_001e: callvirt instance void [mscorlib]System.IDisposable::Dispose()
    L_0023: nop 
    L_0024: endfinally 
    .try L_0009 to L_0015 finally handler L_0015 to L_0025
}

I have no idea how to deal with that ".try ..." part at the end there when using Reflection.Emit.

Can someone point me in the right direction?

© Stack Overflow or respective owner

Related posts about c#

Related posts about reflection.emit